package com.carboy.launch.activity.column;

import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.carboy.launch.R;
import com.carboy.launch.utils.Constants;
import com.carboy.launch.utils.DateUtils;
import com.carboy.launch.widgets.CustomToast;
import com.jwd.clouddog.broadcast.JwdServerBroadCast;
import com.jwd.clouddog.config.JwdConstant;
import com.jwd.clouddog.config.ServerIntent;
import com.pgyersdk.crash.PgyCrashManager;

/**
 * BaseActivity
 */
public class BaseActivity extends Activity {
	// 当前上下文
	private Context mContext;

	// ==================== 状态栏View =============================
	private TextView is_operators_tv = null; // 运营商
	private TextView is_temperature_tv = null; // 温度
	private TextView is_ctime_tv = null; // 时间
	private TextView is_enumber_tv = null; // 电量
	private String imsiType = null; // 卡类型

	private TextView is_gpsnumber_tv; // GPS数量
	private ImageView is_gpsim;// GPS图片
	private TextView is_backstage_tv; // 后台进程

	private ImageView is_signal_igview, is_signal_igview2; // 信号强度
	private TextView is_nettype_tv;
	private RelativeLayout is_signal_rl;
	private ImageView is_network_igview; // wifi状态
	private ImageView is_weather_igview; // 天气状态
	private ImageView is_backrecord_igview; // 后台录制图片
	private ImageView is_power_igview; // 电量状态
	private ImageView isupdata;// 是否需要更新

	private ImageView is_wifistate_igview;// wifi热点状态,WIFI热点连接状态，关闭
											// 不显示，标示后面的数字为当前有多少设备连接
	private TextView is_gpssignal_tv; // wifi热点连接数量
	private final String TAG = "Bas";
	public static final int WIFI_AP_STATE_DISABLING = 10;// wifi热点状态
	public static final int WIFI_AP_STATE_DISABLED = 11;
	public static final int WIFI_AP_STATE_ENABLING = 12;
	public static final int WIFI_AP_STATE_ENABLED = 13;
	public static final int WIFI_AP_STATE_FAILED = 14;
	private boolean say = false;

		private LocationManager mbaselocationManager;
	// ===================== 控件View ============================

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.include_statusbar);

		mContext = BaseActivity.this;
		initStatusBar();

		// 蒲公英测试
		PgyCrashManager.register(this);

		// 电池状态监听
		IntentFilter filter2 = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		filter2.setPriority(1000);
		registerReceiver(mBatInfoReceiver, filter2);

		IntentFilter filter = new IntentFilter();
		filter.addAction(ServerIntent.ACTION_SERVER_WEATHER_DATA);
		filter.addAction(ServerIntent.ACTION_SERVER_GPS_LOCATION_DATA);
		filter.addAction(ServerIntent.ACTION_SERVER_CONNECT_STATE_DATA);
		filter.addAction(ServerIntent.ACTION_SERVER_RUNNING_STATE);
		registerReceiver(conReceive, filter);

		mbaselocationManager = (LocationManager) this
					.getSystemService(Context.LOCATION_SERVICE);
		opSBarTimer(true);

	}

	/**
	 * 自定义的状态栏，初始化状态栏
	 */
	protected void initStatusBar() {
		is_operators_tv = (TextView) this.findViewById(R.id.is_operators_tv); // 运营商
		is_temperature_tv = (TextView) this
				.findViewById(R.id.is_temperature_tv); // 温度
		is_ctime_tv = (TextView) this.findViewById(R.id.is_ctime_tv); // 时间
		is_enumber_tv = (TextView) this.findViewById(R.id.is_enumber_tv); // 电量

		is_wifistate_igview = (ImageView) findViewById(R.id.is_wifistate_igview);// wifi热点状态
		is_gpssignal_tv = (TextView) this.findViewById(R.id.is_gpssignal_tv); // wifi热点连接数量

		is_gpsnumber_tv = (TextView) this.findViewById(R.id.is_gpsnumber_tv); // GPS数量
		is_gpsim = (ImageView) findViewById(R.id.is_gpsim);
		is_backstage_tv = (TextView) this.findViewById(R.id.is_backstage_tv); // 后台进程

		is_signal_igview = (ImageView) this
				.findViewById(R.id.is_signalstrength_igview); // 信号强度
		is_signal_igview2 = (ImageView) this
				.findViewById(R.id.is_signal_igview2); // 没有插卡
		is_signal_rl = (RelativeLayout) findViewById(R.id.is_signal_rl);
		is_nettype_tv = (TextView) this.findViewById(R.id.is_nettype_tv);
		is_network_igview = (ImageView) this
				.findViewById(R.id.is_network_igview); // wifi状态
		is_weather_igview = (ImageView) this
				.findViewById(R.id.is_weather_igview); // 云服务器联机状态标记，正常显示，没连接和连接不成功不显示
		is_backrecord_igview = (ImageView) this
				.findViewById(R.id.is_backrecord_igview); // 后台录制图片

		is_power_igview = (ImageView) this.findViewById(R.id.is_power_igview); // 电量状态
		isupdata = (ImageView) findViewById(R.id.is_backrecord_igview);
		
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		setSignalStrength();

		// 请求天气信息
		JwdServerBroadCast.sendWeatherRequestCast(this);
		// 请求连接状态
		JwdServerBroadCast.sendServerConnectStateRequestCast(this);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// Activity被回收,则保存数据
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// 切屏触发
	}

	/**
	 * 打开App
	 * 
	 * @param pack
	 *            传入包名
	 */
	private void openApply(String pack) {
		try {
			Intent intent = BaseActivity.this.getPackageManager()
					.getLaunchIntentForPackage(pack);
			startActivity(intent);
		} catch (Exception e) {
			// 出现异常,表示找不到APP,报NULL
			CustomToast.showToast(mContext, R.string.intnet_apply_error);
		}
	}

	/**
	 * 设置跳转的的页面
	 * 
	 * @param result
	 *            识别的内容
	 */
	private void jumpIntent(String result) {
	}

	// ==================================== 底部状态栏
	// ==================================
	/**
	 * 电量广播
	 */
	private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			/*
			 * 如果捕捉到的action是ACTION_BATTERY_CHANGED， 就运行onBatteryInfoReceiver()
			 */
			if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
				int intLevel = intent.getIntExtra("level", 0); // 电量
				int intScale = intent.getIntExtra("scale", 100);// 电池满时百分比
				int status = intent.getIntExtra("status", 0);// 状态
				is_enumber_tv.setText(intLevel + "%");

				switch (status) {
				case BatteryManager.BATTERY_STATUS_CHARGING:// 充电状态
					int i1 = getStateIconbyCharge(intLevel);
					is_power_igview.setImageDrawable(mContext.getResources()
							.getDrawable(i1));

					break;
				case BatteryManager.BATTERY_STATUS_NOT_CHARGING:// 没有充电
					int i2 = getStateIcon(intLevel);
					// Toast.makeText(mContext,"放电状态"+i2, 3000).show();
					is_power_igview.setImageDrawable(mContext.getResources()
							.getDrawable(i2));

					break;

				case BatteryManager.BATTERY_STATUS_FULL:// 充满电状态
					is_power_igview.setImageDrawable(mContext.getResources()
							.getDrawable(
									R.drawable.stat_sys_battery_charge_anim5));

					break;
				case BatteryManager.BATTERY_STATUS_UNKNOWN:// 未知状态
					is_power_igview.setImageDrawable(mContext.getResources()
							.getDrawable(R.drawable.stat_sys_battery_unknown));
					break;

				default:
					break;
				}

			}
		}
	};

	// 获得非充电对应的电池状态图标
	public int getStateIcon(int batteryHealth) {

		if (batteryHealth >= 0 && batteryHealth < 10) {
			return R.drawable.stat_sys_battery_1;
		} else if (batteryHealth >= 10 && batteryHealth < 20) {
			return R.drawable.stat_sys_battery_2;
		} else if (batteryHealth >= 20 && batteryHealth < 30) {
			return R.drawable.stat_sys_battery_3;
		} else if (batteryHealth >= 30 && batteryHealth < 40) {
			return R.drawable.stat_sys_battery_4;
		} else if (batteryHealth >= 40 && batteryHealth < 50) {
			return R.drawable.stat_sys_battery_5;
		} else if (batteryHealth >= 50 && batteryHealth < 60) {
			return R.drawable.stat_sys_battery_6;
		} else if (batteryHealth >= 60 && batteryHealth < 70) {
			return R.drawable.stat_sys_battery_7;
		} else if (batteryHealth >= 70 && batteryHealth < 80) {
			return R.drawable.stat_sys_battery_8;
		} else if (batteryHealth >= 80 && batteryHealth < 90) {
			return R.drawable.stat_sys_battery_9;
		} else if (batteryHealth >= 90 && batteryHealth <= 100) {
			return R.drawable.stat_sys_battery_10;
		}
		return R.drawable.stat_sys_battery_unknown;
	}

	// 获得充电时对应的电池状态图标
	public int getStateIconbyCharge(int batteryHealth) {

		if (batteryHealth >= 0 && batteryHealth < 10) {
			return R.drawable.stat_sys_battery_charge_anim1;
		} else if (batteryHealth >= 10 && batteryHealth < 20) {
			return R.drawable.stat_sys_battery_charge_anim2;
		} else if (batteryHealth >= 20 && batteryHealth < 30) {
			return R.drawable.stat_sys_battery_charge_anim3;
		} else if (batteryHealth >= 30 && batteryHealth < 40) {
			return R.drawable.stat_sys_battery_charge_anim4;
		} else if (batteryHealth >= 40 && batteryHealth < 50) {
			return R.drawable.stat_sys_battery_charge_anim5;
		} else if (batteryHealth >= 50 && batteryHealth < 60) {
			return R.drawable.stat_sys_battery_charge_anim6;
		} else if (batteryHealth >= 60 && batteryHealth < 70) {
			return R.drawable.stat_sys_battery_charge_anim7;
		} else if (batteryHealth >= 70 && batteryHealth < 80) {
			return R.drawable.stat_sys_battery_charge_anim8;
		} else if (batteryHealth >= 80 && batteryHealth < 90) {
			return R.drawable.stat_sys_battery_charge_anim9;
		} else if (batteryHealth >= 90 && batteryHealth <= 100) {
			return R.drawable.stat_sys_battery_charge_anim10;
		}
		return R.drawable.stat_sys_battery_charge_unknown;
	}

	/**
	 * 设置状态栏信息，如果出口到国外怎么办？
	 */
	private void setStatusBar() {

		TelephonyManager tm = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imsi = tm.getSubscriberId();
		if (imsi != null) {
			is_signal_rl.setVisibility(View.VISIBLE);
			is_signal_igview2.setVisibility(View.GONE);
			// 因为移动网络编号46000下的IMSI已经用完，所以虚拟了一个46002编号，134/159号段使用了此编号4600401
			if (imsi.startsWith("46000") || imsi.startsWith("46002")
					|| imsi.startsWith("46004") || imsi.startsWith("46007")) { // 中国移动
				imsiType = getResources().getString(R.string.imsi_type_china_mobile);
			} else if (imsi.startsWith("46001") || imsi.startsWith("46006")) { // 中国联通
				imsiType = getResources().getString(R.string.imsi_type_china_unicom);
			} else if (imsi.startsWith("46003") || imsi.startsWith("46005")) { // 中国电信
				imsiType = getResources().getString(R.string.imsi_type_china_telecom);
			} else {
				imsiType = getResources().getString(R.string.imsi_type_unknown);
			}
		} else {
			is_signal_igview2.setVisibility(View.VISIBLE);
			is_signal_rl.setVisibility(View.GONE);
			imsiType = getResources().getString(R.string.imsi_type_no_sim);

		}

		if (isApEnabled(BaseActivity.this)) {
			is_wifistate_igview.setVisibility(View.VISIBLE);
			is_gpssignal_tv.setVisibility(View.VISIBLE);
			is_gpssignal_tv.setText((getConnectedNum() - 1) + "");
		} else {
			is_wifistate_igview.setVisibility(View.GONE);
			is_gpssignal_tv.setVisibility(View.GONE);
		}
		if (Constants.isUpdate) {
			is_temperature_tv.setText(getResources().getString(R.string.has_new_version));
			setUpdateTime();

		} else {
			if (updateTimer != null) {
				is_temperature_tv.setText("");
				updateTimer.cancel();
				updateTimer.purge();
				updateTimer = null;
			}
		}

		is_operators_tv.setText(imsiType);

		is_ctime_tv.setText(DateUtils.getDateNow("yyyy-MM-dd EEEE HH:mm"));
		setwifiPic();
		setRunningAppProcessNumber();
		// com.jwd.clouddog.StartClouddogService com.jwd.clouddog.service
		// boolean isRun = Tool.isServiceRunning(mContext,
		// "com.jwd.clouddog.StartClouddogService");

		
	}

	/**
	 * 操作状态栏定时器,电池广播监听与销毁
	 * 
	 * @param isOpen
	 *            打开与关闭
	 */
	private void opSBarTimer(boolean isOp) {
		if (isOp) {
			setLocationManager();

			

			try {
				// android.net.conn.CONNECTIVITY_CHANGE
				// 网络状态监听
				IntentFilter filter = new IntentFilter(
						ConnectivityManager.CONNECTIVITY_ACTION);
				filter.setPriority(1000);
				registerReceiver(mNetWorkReceiver, filter);
			} catch (Exception e) {
			}
			// 设置定时器参数
			setSBarTime();
		} else {
			try {
				unregisterReceiver(mNetWorkReceiver); // 关闭监听
			} catch (Exception e) {
			}

			imsiType = null; // 清空卡状态
			try {
				if (sBarTimer != null) {
					sBarTimer.cancel();
					sBarTimer.purge();
					sBarTimer = null;
				}
			} catch (Exception e) {
			}
			mbaselocationManager.removeGpsStatusListener(statusListener);
		mbaselocationManager.removeUpdates(locationListener);
		}
	}

	/**
	 * 网络状态监听
	 */
	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent action) {
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action
					.getAction())) {
				try {
					ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo info = connectivityManager
							.getActiveNetworkInfo();
					if (info != null && info.isAvailable()) {
						String name = info.getTypeName();
						if ("WIFI".equals(name)) {
							is_network_igview.setVisibility(View.VISIBLE);
						} else {
							is_network_igview.setVisibility(View.GONE);
						}
					} else {
						is_network_igview.setVisibility(View.GONE);
					}
				} catch (Exception e) {
				}
			}
		}
	};

	/**
	 * wifi连接状态监听
	 */
	private BroadcastReceiver WifiNetWorkReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent action) {
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action
					.getAction())) {
				try {
					ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo info = connectivityManager
							.getActiveNetworkInfo();
					if (info != null && info.isAvailable()) {
						String name = info.getTypeName();
						if ("WIFI".equals(name)) {
							is_network_igview.setVisibility(View.VISIBLE);
							WifiManager wifi_service = (WifiManager) getSystemService(WIFI_SERVICE);
							WifiInfo wifiInfo = wifi_service
									.getConnectionInfo();
							wifiInfo.getRssi();
						} else {
							is_network_igview.setVisibility(View.GONE);
						}
					} else {
						is_network_igview.setVisibility(View.GONE);
					}
				} catch (Exception e) {
				}
			}
		}
	};

	

	// =======================================================
	/**
	 * 获取wifi热点状态
	 */
	public int getWifiApState(Context mContext) {
		WifiManager wifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		try {
			Method method = wifiManager.getClass().getMethod("getWifiApState");
			int i = (Integer) method.invoke(wifiManager);

			return i;
		} catch (Exception e) {

			return WIFI_AP_STATE_FAILED;
		}
	}

	/**
	 * 判断wifi热点状态是否可用
	 * 
	 * @param mContext
	 * @return
	 */
	public boolean isApEnabled(Context mContext) {
		int state = getWifiApState(mContext);
		return WIFI_AP_STATE_ENABLING == state
				|| WIFI_AP_STATE_ENABLED == state;
	}

	/**
	 * 获取链接到当前热点设备数量
	 */
	private int getConnectedNum() {
		ArrayList<String> connectedIP = new ArrayList<String>();
		try {
			BufferedReader br = new BufferedReader(new FileReader(
					"/proc/net/arp"));
			String line;
			while ((line = br.readLine()) != null) {
				String[] splitted = line.split(" +");
				if (splitted != null && splitted.length >= 4) {
					String ip = splitted[0];
					connectedIP.add(ip);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.e(getResources().getString(R.string.seached_wifi_numbers), connectedIP.size() + "");
		return connectedIP.size();
	}

	// =============================================================================
	/**
	 * 获取信号强度
	 */
	private TelephonyManager telephoneManager = null;

	private void setSignalStrength() {
		try {
			telephoneManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

			telephoneManager.listen(phoneStateListener,
					PhoneStateListener.LISTEN_SIGNAL_STRENGTHS|
							PhoneStateListener.LISTEN_DATA_CONNECTION_STATE|
							PhoneStateListener.LISTEN_DATA_ACTIVITY
			);
		} catch (Exception e) {
			// is_gpssignal_tv.setText("0");
		}
	}

	int type = 0;
	PhoneStateListener phoneStateListener = new PhoneStateListener() {

		@Override
		public void onDataActivity(int direction) {
			super.onDataActivity(direction);
			type = telephoneManager.getNetworkType();
			setNetworkType(type);
		}

		@Override
		public void onDataConnectionStateChanged(int state, int networkType) {
			super.onDataConnectionStateChanged(state, networkType);
			setNetworkType(networkType);
		}
		private void setNetworkType(int networkType){
			switch (networkType) {

				case TelephonyManager.NETWORK_TYPE_EDGE:
					is_nettype_tv.setText("E");
					break;

				case TelephonyManager.NETWORK_TYPE_UMTS:
					is_nettype_tv.setText("3G");
					break;
				case TelephonyManager.NETWORK_TYPE_HSDPA:
				case TelephonyManager.NETWORK_TYPE_HSUPA:
				case TelephonyManager.NETWORK_TYPE_HSPA:
				case TelephonyManager.NETWORK_TYPE_HSPAP:
					is_nettype_tv.setText("3G");
					break;
				case TelephonyManager.NETWORK_TYPE_CDMA:
					is_nettype_tv.setText("2G");
					break;

				case TelephonyManager.NETWORK_TYPE_1xRTT:
					is_nettype_tv.setText("2G");
					break;

				case TelephonyManager.NETWORK_TYPE_EVDO_0: // fall through
				case TelephonyManager.NETWORK_TYPE_EVDO_A:
				case TelephonyManager.NETWORK_TYPE_EVDO_B:
				case TelephonyManager.NETWORK_TYPE_EHRPD:
					is_nettype_tv.setText("3G");
					break;
				case TelephonyManager.NETWORK_TYPE_LTE:
					is_nettype_tv.setText("4G");
					break;
				case TelephonyManager.NETWORK_TYPE_UNKNOWN:
				default:
					is_nettype_tv.setText("E");
					break;
			}
		}

		@Override
		public void onSignalStrengthsChanged(SignalStrength signalStrength) {
			// TODO Auto-generated method stub
			super.onSignalStrengthsChanged(signalStrength);
			String strength = String.valueOf(signalStrength
					.getGsmSignalStrength());
			// 在android手机上，通过“设置”-“关于手机”-“状态”-“信号强度”可以查看到手机的信号强度，显示出如“-87 dBm 13
			// asu”这样的数据。ASU与dBm之间的关系是：dBm=-113+（2*ASU）。

			// 在你手机屏幕上方显示的信号条永远不会是最好的方法来确定你手机的信号，无论你用什么手机都一样。Android也是，用很粗的条来展示很强的信号，但这些条仅仅表示最高的信号。
			// 或许你并不熟悉，信号通常是以dBm度量的。dBm是每毫瓦特的电磁波产生的功率。-60dBm的信号接近完美，-112dBm就很容易掉线，如果你在
			// -87dBm以上，Android会显示一个4格的满信号。
			int asu = signalStrength.getGsmSignalStrength();
			int lastSignal = -113 + 2 * asu;
			type = telephoneManager.getNetworkType();
			int level = Math.abs(lastSignal);
			// Toast.makeText(mContext, "当前信号强度"+level,3000).show();
			// Toast.makeText(mContext, "当前信号类型"+type,3000).show();
			is_signal_igview.setImageResource(R.drawable.phonesinal_list);
			is_signal_igview.setImageLevel(level);
			setNetworkType(type);
			// StringBuffer sb = new StringBuffer(); if (type ==
			// TelephonyManager.NETWORK_TYPE_UMTS || type ==
			// TelephonyManager.NETWORK_TYPE_HSDPA) {
			// sb.append("联通3g").append("信号强度:").append(strength); } else if
			// (type == TelephonyManager.NETWORK_TYPE_GPRS || type ==
			// TelephonyManager.NETWORK_TYPE_EDGE) {
			// sb.append("移动或者联通2g").append("信号强度:").append(strength); }else
			// if(type==TelephonyManager.NETWORK_TYPE_CDMA){
			// sb.append("电信2g").append("信号强度:").append(strength); }else
			// if(type==TelephonyManager.NETWORK_TYPE_EVDO_0
			// ||type==TelephonyManager.NETWORK_TYPE_EVDO_A){
			// sb.append("电信3g").append("信号强度:").append(strength); }else{
			// sb.append("非以上信号").append("信号强度:").append(strength); }
			//

		}
	};

	// =============================================================================
	/**
	 * 获取后台运行的程序
	 */
	private void setRunningAppProcessNumber() {
		try {
			// 获得ActivityManager服务的对象
			ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
			// 通过调用ActivityManager的getRunningAppProcesses()方法获得系统里所有正在运行的进程
			List<ActivityManager.RunningAppProcessInfo> appProcessList = mActivityManager
					.getRunningAppProcesses();

			List<ActivityManager.RunningAppProcessInfo> appProcessList2 = new ArrayList<ActivityManager.RunningAppProcessInfo>();

			PackageManager pm = mContext.getPackageManager();

			ArrayList<PackageInfo> allPackageInfos = getAllApps();

			for (int k = 0; k < allPackageInfos.size(); k++) {
				String pName = allPackageInfos.get(k).packageName;
				for (int j = 0; j < appProcessList.size(); j++) {
					if (appProcessList.get(j).processName.equals(pName)) {
						//Log.e("Bas1", appProcessList.get(j).processName);
						appProcessList2.add(appProcessList.get(j));
					}
				}
			}
			
			is_backstage_tv.setText(appProcessList2.size() + "");
		} catch (Exception e) {
			is_backstage_tv.setText("0");
		}
	}

	
	// =============================================================================
	/**
	 * 获取卫星数量
	 * */

	private void setLocationManager() {
		try {

			if (mbaselocationManager
					.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

				String provider = LocationManager.GPS_PROVIDER;
				Location location = mbaselocationManager
						.getLastKnownLocation(provider);

				mbaselocationManager.requestLocationUpdates(provider, 1000, 1, locationListener);
				mbaselocationManager.addGpsStatusListener(statusListener);
				return;
			}
			// CustomToast.showToast(mContext, "请开启GPS！");
			// Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
			// startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 卫星状态监听器
	 */

	private List<GpsSatellite> numSatelliteList = new ArrayList<GpsSatellite>(); // 卫星信号
	private final GpsStatus.Listener statusListener = new GpsStatus.Listener() {
		public void onGpsStatusChanged(int event) { // GPS状态变化时的回调，如卫星数

			GpsStatus status = mbaselocationManager.getGpsStatus(null); // 取当前状态
			String satelliteInfo = updateGpsStatus(event, status);
			if (Integer.parseInt(satelliteInfo) > 0) {
				is_gpsim.setImageResource(R.drawable.icon_gpsrun);
				is_gpsnumber_tv.setText(satelliteInfo);
			} else {
				is_gpsim.setImageResource(R.drawable.icon_gpsno);
				is_gpsnumber_tv.setText("");
			}

		}
	};
	LocationListener locationListener = new LocationListener() {
		@Override
		public void onLocationChanged(Location location) {
		}
	
		@Override
		public void onStatusChanged(String provider, int status,
				Bundle extras) {
		}
	
		@Override
		public void onProviderEnabled(String provider) {
		}
	
		@Override
		public void onProviderDisabled(String provider) {
		}
	};

	/**
	 * 返回卫星个数
	 */
	private String updateGpsStatus(int event, GpsStatus status) {
		if (status != null && event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
			try {
				int maxSatellites = status.getMaxSatellites();
				Iterator<GpsSatellite> it = status.getSatellites().iterator();
				numSatelliteList.clear();
				int count = 0;
				while (it.hasNext() && count <= maxSatellites) {
					GpsSatellite s = it.next();
					numSatelliteList.add(s);
					boolean b = s.usedInFix();
					if (b) {
						count++;
					}

				}
				return count + "";
			} catch (Exception e) {
				return "0";
			}
		} else {
			return "0";
		}
	}

	Timer updateTimer;
	TimerTask updateTask; // 定时器任务栈

	/** 设置定时器参数 */
	private void setUpdateTime() {
		if (updateTimer == null) {
			updateTimer = new Timer(); // 每次重新new 防止被取消
			// 重新生成定时器 防止出现TimerTask is scheduled already 所以同一个定时器任务只能被放置一次
			updateTask = new TimerTask() {
				@Override
				public void run() {
					// // 需要做的事:发送消息
					updateHandler.sendEmptyMessage(1);
				}
			};
			// 5秒获取一次
			updateTimer.schedule(updateTask, 0, 1000); // 开启定时器
		}
	}

	Handler updateHandler = new Handler() {
		public void handleMessage(Message msg) {
		
				try {

					if (is_temperature_tv.getVisibility()==View.VISIBLE) {
						is_temperature_tv.setVisibility(View.GONE);
						
					} else if(is_temperature_tv.getVisibility()==View.GONE){
						
						is_temperature_tv.setVisibility(View.VISIBLE);
					}
				} catch (Exception e) {
				
			}
			super.handleMessage(msg);
		};
	};

	// =============================================================================

	/** 设置定时器参数 */
	private void setSBarTime() {
		sBarTimer = new Timer(); // 每次重新new 防止被取消
		// 重新生成定时器 防止出现TimerTask is scheduled already 所以同一个定时器任务只能被放置一次
		sBarTask = new TimerTask() {
			@Override
			public void run() {
				// // 需要做的事:发送消息
				// Message message = new Message();
				// message.what = 1;
				sBarHandler.sendEmptyMessage(1);
			}
		};
		// 5秒获取一次
		sBarTimer.schedule(sBarTask, 0, 3000); // 开启定时器
	}

	Timer sBarTimer; // 定时器
	TimerTask sBarTask; // 定时器任务栈
	Handler sBarHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				try {
					setStatusBar();
					// contrallcloudService();
					//
				} catch (Exception e) {
				}
			}
			super.handleMessage(msg);
		};
	};
	// =================================================
	// =================================================
	/**
	 * 天气预报,gps,云狗连接状态
	 */
	public static double lastcBearing = 0;
	public static int curSpeedAdjust = 0; // curSpeed和补偿值运算后的速度
	private BroadcastReceiver conReceive = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(ServerIntent.ACTION_SERVER_WEATHER_DATA)) {
				// 接收天气信息
				String weatherDateBroadcast = intent
						.getStringExtra(JwdConstant.WEATHER_DATA_BROADCAST);
				String weatherDateShow = intent
						.getStringExtra(JwdConstant.WEATHER_DATA_SHOW);
				// Log.i("WEATHER", "当前天气：" + weatherDateBroadcast);
				if (!Constants.isUpdate) {
					is_temperature_tv.setText(weatherDateShow);
					is_temperature_tv.setVisibility(View.VISIBLE);
					is_ctime_tv.setVisibility(View.GONE);
				}
			} else if (action
					.equals(ServerIntent.ACTION_SERVER_CONNECT_STATE_DATA)) {
				// 接收连接状态
				boolean connectState = intent.getBooleanExtra(
						JwdConstant.SERVER_CONNECT_STATE, false);
				com.carboy.launch.utils.Constants.clouddogConected = connectState;

				if (connectState) {
					is_weather_igview.setVisibility(View.VISIBLE);
				} else {
					is_weather_igview.setVisibility(View.GONE);

				}
				//Log.i("<--->", "接收服务器连接状态:" + connectState);

			}
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// opSBarTimer(false);
		unregisterReceiver(conReceive);
		unregisterReceiver(mBatInfoReceiver);
		opSBarTimer(false);
	}

	public boolean isWifiConnect() {
		ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		NetworkInfo mWifi = connManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		return mWifi.isConnected();
	}

	public static int getnet(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkINfo = cm.getActiveNetworkInfo();
		int type = 0;

		if (networkINfo != null) {
			if (networkINfo.getType() == ConnectivityManager.TYPE_MOBILE) {
				type = 1;
			}
			if (networkINfo.getType() == ConnectivityManager.TYPE_WIFI) {
				type = 2;
			}
		} else {
			type = 0;
		}
		return type;
	}

	// public boolean isDataConnect() {
	// ConnectivityManager connManager = (ConnectivityManager)
	// getSystemService(CONNECTIVITY_SERVICE);
	// NetworkInfo data = connManager
	// .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
	// return data.isConnected();
	// }

	private void setwifiPic() {
		int type = getnet(mContext);
		switch (type) {
		case 0:
			is_network_igview.setVisibility(View.GONE);
			break;
		case 1:
			// 手机网络连接
			is_network_igview.setVisibility(View.VISIBLE);
			is_network_igview.setImageResource(R.drawable.data_connect);
			break;
		case 2:
			// wifi网络连接
			WifiManager wifi_service = (WifiManager) getSystemService(WIFI_SERVICE);
			WifiInfo wifiInfo = wifi_service.getConnectionInfo();
			int level = Math.abs(wifiInfo.getRssi());
			is_network_igview.setVisibility(View.VISIBLE);
			is_network_igview.setImageResource(R.drawable.wifisinal_list);
			is_network_igview.setImageLevel(level);
			break;
		default:
			break;
		}

	}

	private ApplicationInfo is1(PackageManager pm, String mProcessName, int mUid) {

		try {
			ApplicationInfo ai = pm.getApplicationInfo(mProcessName,
					PackageManager.GET_UNINSTALLED_PACKAGES);

			if (ai.uid == mUid) {
				return ai;
			} else {
				return null;
			}

		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	private ApplicationInfo is2(PackageManager pm, String mProcessName, int mUid) {
		String[] pkgs = pm.getPackagesForUid(mUid);
		try {
			if (pkgs.length == 1) {
				ApplicationInfo ai = pm.getApplicationInfo(pkgs[0],
						PackageManager.GET_UNINSTALLED_PACKAGES);
				return ai;

			} else {
				return pm.getApplicationInfo(pkgs[0],
						PackageManager.GET_UNINSTALLED_PACKAGES);

			}
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	public boolean initFlags(ApplicationInfo pi) {
		if ((pi.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取全部app信息
	 */
	public ArrayList<PackageInfo> getAllApps() {
		ArrayList<PackageInfo> apps = new ArrayList<PackageInfo>();
		PackageManager pManager = mContext.getPackageManager();
		// 获取手机内所有应用
		List<PackageInfo> packlist = pManager.getInstalledPackages(0);
		for (int i = 0; i < packlist.size(); i++) {
			PackageInfo pak = (PackageInfo) packlist.get(i);

			// 判断是否为非系统预装的应用程序
			// 这里还可以添加系统自带的，这里就先不添加了，如果有需要可以自己添加
			// if()里的值如果<=0则为自己装的程序，否则为系统工程自带
//			if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
				// 添加自己已经安装的应用程序
				apps.add(pak);
//			}

		}
		return apps;
	}
}
